package main

import (
	"fmt"
	"net/http"
	"strings"
	"log"
	"text/template"
	"time"
)

func sayhellName(w http.ResponseWriter, r *http.Request){
	r.ParseForm()	//解析参数，默认是不会解析的

	fmt.Println("path", r.Form)		//这些信息是输出到服务器的打印信息
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])

	for k,v := range r.Form{
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v,""))
	}

	fmt.Fprintf(w, "Hello astaxie!" + strings.Join(r.Form["url_long"],""))
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("E:/mycode/go/src/Go Web编程/6.1/login.gtpl")


		expiration := time.Now()
		expiration = expiration.AddDate(1,0,0)
		cookie := http.Cookie{Name:"username",Value:"zhangqidong",Expires:expiration}
		http.SetCookie(w, &cookie)
		fmt.Println("cookie设置完成")
		log.Println(t.Execute(w, nil))
	} else {
		//请求的是登陆数据，那么执行登陆的逻辑判断
		r.ParseForm()
		fmt.Println("username:", r.Form["username"])
		fmt.Println("password:", r.Form["password"])
		cookie, _ := r.Cookie("username")
		fmt.Fprint(w, cookie)
		fmt.Println("cookie读取完成",cookie)
	}
}

func main()  {
	http.HandleFunc("/", sayhellName)	//设置反问的路由
	http.HandleFunc("/login", login)	//设置反问的路由

	err := http.ListenAndServe(":9090",nil)
	if err != nil{
		log.Fatal("ListenAndServe:",err)
	}
}